<template>
    <el-card class="b-table-operation" shadow="never">
        <input v-if="configObj.import" type="file" @input="onFileInput" ref="fileInput" id="fileInput"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            style="display: none" />
        <el-button v-for="btn in buttonGroupObj" :ref="btn.key" :key="btn.key" :type="btn.type" :icon="btn.icon"
            size="mini" @click="onClick(btn)" :loading="btn.loading || loading[btn.key]">{{ btn.label
            }}</el-button>
        <slot name="content"></slot>
        <!-- <right-toolbar :search="configObj.search ? true : false" @showSearch="showSearch"
            :refresh="configObj.refresh ? true : false" @queryTable="refreshTable"></right-toolbar> -->
    </el-card>
</template>

<script>
import { throttle } from '@/utils';

export default {
    name: 'bTableOperation',
    props: {
        params: {
            type: Object,
            default: () => ({})
        },
        config: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            loading: {},
            buttonGroup: {
                add: {
                    label: '新增',
                    key: 'add',
                    icon: 'el-icon-plus',
                    type: 'primary'
                },
                export: {
                    label: '导出',
                    key: 'export',
                    icon: 'el-icon-download',
                    type: 'warning',
                },
                import: {
                    label: '导入',
                    key: 'import',
                    icon: 'el-icon-upload2',
                    type: 'primary'
                },
                template: {
                    label: '下载模板',
                    key: 'template',
                    icon: 'el-icon-download',
                    type: 'warning'
                }
            },
            /** 当前点击的按钮 */
            currentBtn: null
        }
    },
    computed: {
        configObj() {
            return { ...this.config }
        },
        buttonGroupObj() {
            let arr = []
            for (const key in this.configObj) {
                if (['refresh', 'search'].includes(key)) continue;
                let obj = this.configObj[key]
                if (obj.permission && !this.$auth.hasPermi(obj.permission)) continue;
                if (obj.role && !this.$auth.hasRole(obj.role)) continue;

                let btn = this.buttonGroup[key]
                arr.push({ ...btn, ...obj })

                this.$set(this.loading, key, false)
            }
            return arr
        }
    },
    methods: {
        onClick(btn) {
            this.currentBtn = btn;
            switch (btn.key) {
                case 'import':
                    this.$refs.fileInput.click()
                    break;
                case 'export':
                    this.handleExport()
                    break;
                default:
                    btn.onClick && btn.onClick(btn)
                    break;
            }
        },
        showSearch() {
            this.configObj?.search?.onClick()
        },
        refreshTable() {
            this.configObj?.refresh?.onClick()
        },

        // 处理文件选择后的逻辑
        onFileInput(event) {
            const btn = this.currentBtn
            if (!btn.api || typeof btn.api != 'function') {
                throw (new Error('未配置导入接口'))
            }
            const file = event.target.files[0]
            event.target.value = ''
            if (!file) {
                return this.$modal.msgError('请选择需要导入的文件');
            }
            this.loading[btn.key] = true;
            // 创建一个FormData对象
            const formData = new FormData();
            console.log("file", file);
            formData.append("file", file); // 'file'是后端接收文件时使用的字段名
            btn.api && btn.api(formData)
                .then((res) => {
                    this.$modal.msgSuccess("导入成功");
                    btn.onSuccess && btn.onSuccess()
                })
                .catch((err) => {
                    this.$modal.msgError('导入失败');
                })
                .finally(() => {
                    this.loading[btn.key] = false;
                })
        },

        handleExport() {
            const btn = this.currentBtn
            this.$modal
                .confirm(btn.message || "是否确认导出当前所有数据项?")
                .then(() => {
                    this.loading['export'] = true;
                    if (!btn.api || typeof btn.api != 'function') {
                        throw (new Error('未配置导出接口'))
                    }
                    return btn.api && btn.api({ ...this.params, pageNo: undefined, pageSize: undefined });
                })
                .then((response) => {
                    this.$download.excel(response, btn.fileName || "导出数据.xls");
                    this.loading['export'] = false;
                })
                .catch((error) => {
                    console.error(error);
                    this.loading['export'] = false;
                });
        }
    }
}
</script>

<style lang="scss" scoped>
.b-table-operation {
    border-radius: 4px 4px 0 0;

    :deep(.el-card__body) {
        padding-bottom: 0;
        width: 100%;
        display: flex;
        align-items: center;

        .top-right-btn {
            margin-left: auto;
        }
    }

    &+:deep(.b-table) {
        border-radius: 0 0 4px 4px;
    }
}
</style>